<template>
  <div>
    <el-form :inline="true">
      <el-form-item prop="province">
        <el-form-item>
          <v-distpicker @selected="onSearchSelected" :provinceOut="searchOutsourcer.provinceCode" only-province>
          </v-distpicker>
        </el-form-item>
      </el-form-item>
      <el-form-item prop="company">
        <el-input v-model.trim="searchOutsourcer.company" placeholder="公司名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/外包商导入模板.xlsx" download="外包商导入模板.xlsx"
               style="color:#5a5e66;text-decoration: none ">
              <el-dropdown-item command="handleDownload">模板下载
              </el-dropdown-item>
            </a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="excelExport">数据导出</el-button>
      </el-form-item>
    </el-form>

    <custom-table
      :columns="columns"
      :data="outsourcerList"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <!-- 外包商模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogType ==='add'? '新增外包商':'外包商信息修改'" :visible.sync="dialogVisible"
               :close-on-click-modal="false">
      <el-form :model="outsourcerDto" :rules="outsourcerRules" label-width="120px" ref="outsourcerForm">
        <el-form-item label="公司名称" prop="company">
          <el-input v-model="outsourcerDto.company" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="外包商类型" prop="type">
          <el-select v-model="outsourcerDto.type" placeholder="请选择外包商类型">
            <el-option
              v-for="item in outsourcerTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在地区">
          <el-row>
            <el-col :span="8" prop="provinceRule">
              <el-select v-model="outsourcerDto.provinceCode" clearable placeholder="请选择省份" @change="getCity()">
                <el-option
                  v-for="item in allProvince"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="8" prop="cityRule">
              <el-select v-model="outsourcerDto.cityCode" clearable placeholder="请选择城市" @change="getArea()">
                <el-option
                  v-for="item in allCityInfo"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="8" prop="areaRule">
              <el-select v-model="outsourcerDto.areaCode" clearable placeholder="请选择地区">
                <el-option
                  v-for="item in allAreaInfo"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="outsourcerDto.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="contact">
          <el-input v-model="outsourcerDto.contact" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="outsourcerDto.tel" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流联系人" prop="logisticsContact">
          <el-input v-model="outsourcerDto.logisticsContact" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流联系电话" prop="logisticsTel">
          <el-input v-model="outsourcerDto.logisticsTel" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {apiOutsourcerReadExcel} from '@/api/excel/excelRead'
  import store from '@/store'
  import {
    apiGetOutsourcerList,
    apiGetOutsourcerById,
    apiDelOutsourcer,
    apiAddOutsourcer,
    apiUpdOutsourcer,
    apiExport
  } from '@/api/basic/info/outsourcer'
  import {baseInfo} from '@/utils/fetch'
  import {apiGetCity, apiGetArea} from '@/api/dictionary'
  import {downloadExcel} from "../../../utils";

  export default {
    name: 'outsourcer',
    components: {CustomTable},
    data () {
      return {
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        searchOutsourcer: {
          provinceCode: '',
          company: ''
        },
        listQuery: {
          provinceCode: undefined,
          cityCode: undefined,
          company: undefined
        },
        tableLoadingFlag: false,
        dialogVisible: false,
        uploadVisible: false,
        hideTable: false,
        dialogType: '',
        permission: {auth: false, edit: true, del: true},
        filePath: '',
        // 所有省份
        allProvince: [],
        // 所有城市
        allCityInfo: [],
        // 所有地区
        allAreaInfo: [],
        outsourcerDto: {
          // code: '',
          company: '',
          contact: '',
          tel: '',
          logisticsContact: '',
          logisticsTel: '',
          provinceCode: undefined,
          cityCode: undefined,
          areaCode: undefined,
          province: '',
          city: '',
          area: '',
          address: undefined,
          type: ''
        },
        outsourcerTypeOptions: [
          {id: 2, name: '国家级'},
          {id: 1, name: '省级'},
          {id: 0, name: '地市级'}
        ],
        outsourcerRules: {
          company: [
            {required: true, message: '请输入公司名称', trigger: 'blur'},
            {max: 50, message: '公司名称不超过 50 个字符', trigger: 'blur'}
          ],
          address: [
            {required: true, message: '请输入外包商详细地址', trigger: 'blur'},
            {max: 255, message: '长度不超过 255 个字符', trigger: 'blur'}
          ],
          contact: [
            {required: true, message: '请输入联系人姓名', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          tel: [
            {required: true, message: '请输入联系人电话', trigger: 'blur'}
          ],
          logisticsContact: [
            {required: true, message: '请输入物流联系人', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          logisticsTel: [
            {required: true, message: '请输入物流联系人电话', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请选择外包商类型', trigger: 'blur'}
          ],
          provinceRule: [
            {required: true, message: '请选择省份', trigger: 'change'}
          ],
          cityRule: [
            {required: true, message: '请选择城市', trigger: 'change'}
          ],
          areaRule: [
            {required: true, message: '请选择地区', trigger: 'change'}
          ]
        },
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '类型', name: 'type', align: 'center'},
          {label: '省份', name: 'province', align: 'center'},
          {label: '城市', name: 'city', align: 'center'},
          {label: '地区', name: 'area', align: 'center'},
          {label: '公司名称', name: 'company', align: 'center'}
        ],
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', width: '77', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', width: '120', height: '40', align: 'center'},
          {label: '公司名称', name: 'company', width: '80', height: '40', align: 'center'},
          {label: '省份', name: 'province', width: '80', height: '40', align: 'center'},
          {label: '城市', name: 'city', width: '80', height: '40', align: 'center'},
          {label: '地区', name: 'area', width: '80', height: '40', align: 'center'},
          {label: '详细地址', name: 'address', width: '80', height: '40', align: 'center'},
          {label: '联系人', name: 'contact', width: '80', height: '40', align: 'center'},
          {label: '联系电话', name: 'tel', width: '80', height: '40', align: 'center'},
          {label: '物流联系人', name: 'logisticsContact', width: '80', height: '40', align: 'center'},
          {label: '物流联系电话', name: 'logisticsTel', width: '80', height: '40', align: 'center'},
          {label: '外包商类型', name: 'outsourcerType', width: '80', height: '40', align: 'center'}
        ],
        operationColumn: {
          width: '150',
          operations: [
            {name: '外包点', callback: this.onBtnOutsourcerPoint},
            {name: '编辑', callback: this.handleEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        outsourcerList: [],
        wrongDataListL: [],
        pagination: this.getData(this.getOutsourcerList)
      }
    },
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getOutsourcerList(listQuery)
      this.getAllProvince()
    },
    methods: {
      excelExport () {
        let paramsPost = {
          provinceCode: this.searchOutsourcer.provinceCode,
          company: this.searchOutsourcer.company
        }
        apiExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后外包商信息导出表')
        }).catch(err => {
          console.log(err)
        })
      },
      uploadSuccess (response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功'
        })
        let filePath = response.data
        this.excelRead(filePath)
      },
      // 上传错误
      uploadError (err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }
        return extension && isLt2M
      },
      excelRead (filePath) {
        apiOutsourcerReadExcel(filePath).then(response => {
          if (response.data) {
            this.wrongDataList = response.data
            this.hideTable = true
          } else {
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后',
              type: 'success'
            })
            this.hideTable = false
            this.getOutsourcerList({
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            })
          }
          this.fileList = []
        })
      },
      handleCommand (command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      },
      onSearchSelected (data) {             // 省市区联动回调
        this.searchOutsourcer.provinceCode = data.province.code
        this.searchOutsourcer.cityCode = data.city.code
      },
      getAllProvince () {
        apiGetCity().then(response => {
          this.allProvince = response.data
        })
      },
      getCity () {
        this.outsourcerDto.cityCode = ''
        if (this.outsourcerDto.provinceCode === '') {
          this.allCityInfo = []
        }
        let listQuery = {
          province: this.outsourcerDto.provinceCode
        }
        apiGetCity(listQuery).then(response => {
          this.allCityInfo = response.data
        })
      },
      getArea () {
        this.outsourcerDto.areaCode = ''
        if (this.outsourcerDto.cityCode === '') {
          this.allAreaInfo = []
        }
        let listQuery = {
          city: this.outsourcerDto.cityCode
        }
        apiGetArea(listQuery).then(response => {
          this.allAreaInfo = response.data
        })
      },
      getOutsourcerList (listQuery) {
        this.listLoadingFlag = true
        if (listQuery.provinceCode === undefined) {
          listQuery.provinceCode = this.searchOutsourcer.provinceCode
        }
        if (listQuery.cityCode === undefined) {
          listQuery.cityCode = this.searchOutsourcer.cityCode
        }
        if (listQuery.company === undefined) {
          listQuery.company = this.searchOutsourcer.company
        }
        apiGetOutsourcerList(listQuery).then(response => {
          this.outsourcerList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.listLoadingFlag = false
        }).catch(() => {
          this.listLoadingFlag = false
        })
      },
      handleAdd () {
        this.outsourcerDto = {
          // code: '',
          company: '',
          contact: '',
          tel: '',
          logisticsContact: '',
          logisticsTel: '',
          provinceCode: undefined,
          cityCode: undefined,
          areaCode: undefined,
          province: '',
          city: '',
          area: '',
          address: '',
          type: ''
        }
        if (this.$refs['outsourcerForm']) {
          this.$refs['outsourcerForm'].resetFields()
        }
        this.dialogType = 'add'
        this.dialogVisible = true
      },
      handleEdit (row) {
        apiGetOutsourcerById(row.id).then(response => {
          this.outsourcerDto.provinceCode = response.data.provinceCode
          this.getCity()
          this.outsourcerDto.cityCode = response.data.cityCode
          this.getArea()
          this.outsourcerDto = response.data
          this.dialogType = 'edit'
          this.dialogVisible = true
        })
      },
      handleDel (row) {
        this.$confirm('确定删除该外包商?', '删除外包商', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiDelOutsourcer(row.id).then(() => {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功!'
            })
            this.getOutsourcerList(this.listQuery)
          })
        }).catch(() => {
        })
      },
      onBtnOutsourcerPoint (row) {
        this.$router.push({
          path: '/basic/info/outsourcerPoint',
          query: {
            outsourcerId: row.id,
            provinceCode: row.provinceCode,
            cityCode: row.cityCode,
            areaCode: row.areaCode,
            province: row.province,
            city: row.city,
            area: row.area,
            type: row.type
          }
        })
      },
      submit () {
        this.$refs['outsourcerForm'].validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      addSubmit () {
        apiAddOutsourcer(this.outsourcerDto).then(() => {
          this.$message({
            showClose: true,
            message: '新增成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.getOutsourcerList(this.listQuery)
        })
      },
      updSubmit () {
        apiUpdOutsourcer(this.outsourcerDto).then(() => {
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.getOutsourcerList(this.listQuery)
        })
      },
      cancel () {
        this.dialogVisible = false
        this.$refs['outsourcerForm'].resetFields()
      },
      searchData () {
        this.listQuery.provinceCode = this.searchOutsourcer.provinceCode
        this.listQuery.cityCode = this.searchOutsourcer.cityCode
        this.listQuery.company = this.searchOutsourcer.company
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getOutsourcerList(this.listQuery)
      }
    }
  }
</script>
<style type="text/css">
  select[data-v-a078dc08] {
    font-size: 14px;
    height: 36px;
    border: 1px solid #bfcbd9;
  }
</style>
